/*
 * Copyright 2008-2023 dexian.vip. All rights reserved.
 * Support: http://www.dexian.vip
 * License: http://www.dexian.vip/license
 */

package vip.dexian.common.utils;

import org.springframework.beans.BeansException;
import org.springframework.beans.factory.DisposableBean;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;
import org.springframework.context.annotation.Lazy;
import org.springframework.stereotype.Component;
import org.springframework.util.Assert;
import org.springframework.web.servlet.LocaleResolver;

import java.util.Locale;

/**
 * Spring工具类，用于获取Spring Bean
 *
 * @author 挺好的 2023年05月30日 8:06
 */
@Lazy (false)
@Component
public final class SpringUtils implements ApplicationContextAware, DisposableBean {

    /**
     * spring应用上下文
     */
    private static ApplicationContext applicationContext;

    private SpringUtils () {
    }

    /**
     * 获取Spring管理的Bean
     *
     * @param name
     *         bean名称
     * @param type
     *         bean 类型
     * @param <T>
     *         指定 Class类型的bean
     *
     * @return bean
     */
    public static <T> T getBean (String name, Class <T> type) {
        Assert.hasText(name, "bean名称不能为空");
        Assert.notNull(type, "bean 类型不能为空");

        return SpringUtils.applicationContext.getBean(name, type);
    }

    /**
     * 获取国际化资源文件中的消息
     *
     * @param code
     *         消息key
     * @param args
     *         占位参数
     *
     * @return 消息
     */
    public static String getMessage (String code, Object... args) {
        Assert.hasText(code, "code不能为空");

        LocaleResolver localeResolver = getBean("localeResolver", LocaleResolver.class);
        Locale locale = localeResolver.resolveLocale(null);


        return SpringUtils.applicationContext.getMessage(code, args, locale);
    }

    /**
     * @return 获取应用上下文
     */
    public static ApplicationContext getApplicationContext () {
        return SpringUtils.applicationContext;
    }

    /**
     * 销毁
     */
    @Override
    public void destroy () throws Exception {
        SpringUtils.applicationContext = null;
    }

    /**
     * 设置spring应用上下文
     *
     * @param applicationContext
     *         {@link ApplicationContext}
     */
    @Override
    public void setApplicationContext (ApplicationContext applicationContext) throws BeansException {
        SpringUtils.applicationContext = applicationContext;
    }
}
